package org.soc.timesheet.controller;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.soc.timesheet.custom.domain.filters.ProjectFilter;
import org.soc.timesheet.custom.domain.filters.RolesFilter;
import org.soc.timesheet.domain.Projects;
import org.soc.timesheet.domain.Roles;
import org.soc.timesheet.server.domain.service.FunctionsService;
import org.soc.timesheet.server.domain.service.RolesService;
import org.soc.timesheet.server.domain.service.SubFunctionsService;
import org.soc.timesheet.server.domain.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.UriComponentsBuilder;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;
import org.springframework.roo.addon.web.mvc.controller.json.RooWebJson;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@RequestMapping("/roleses")
@Controller
@RooWebScaffold(path = "roleses", formBackingObject = Roles.class)
@RooWebJson(jsonObject = Roles.class)
public class RolesController {
	
	
	
	@RequestMapping(value = "/{page}/{limit}", headers = "Accept=application/json", method = RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<Page<Roles>> findAll(
			@PathVariable("page") int page, @PathVariable("limit") int size,
			@RequestHeader(value="filters",required=false) String filters) throws Exception {
		PageRequest pageRequest = new PageRequest(page, size);
		if(filters!= null && !filters.equals("")){
			return findByFilters(filters, pageRequest);
		}
		return find(pageRequest);
	}
	
	private ResponseEntity<Page<Roles>> find(PageRequest pageRequest) {
		HttpHeaders headers = getHeaders();
		Page<Roles> result = rolesService.findAll(pageRequest);
		return new ResponseEntity<Page<Roles>>(result, headers,
				HttpStatus.OK);
	}
	private ResponseEntity<Page<Roles>> findByFilters(String filters,
			PageRequest pageRequest) throws IOException, JsonParseException,
			JsonMappingException {
		ObjectMapper mapper = new ObjectMapper();
		RolesFilter filter = mapper.readValue(filters, new TypeReference<RolesFilter>() {
		});
		Page<Roles> page =  rolesService.findByFilters(filter,pageRequest);
		return new ResponseEntity<Page<Roles>>(page, getHeaders(),
				HttpStatus.OK);
	}
	private HttpHeaders getHeaders() {
		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-Type", "application/json");
		return headers;
	}


	@RequestMapping(value = "/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
    @ResponseBody
    public ResponseEntity<String> showJson(@PathVariable("id") Integer id) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json; charset=utf-8");
        try {
            Roles roles = rolesService.findRoles(id);
            if (roles == null) {
                return new ResponseEntity<String>(headers, HttpStatus.NOT_FOUND);
            }
            return new ResponseEntity<String>(roles.toJson(), headers, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<String>("{\"ERROR\":"+e.getMessage()+"\"}", headers, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

	@RequestMapping(headers = "Accept=application/json")
    @ResponseBody
    public ResponseEntity<String> listJson() {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json; charset=utf-8");
        try {
            List<Roles> result = rolesService.findAllRoleses();
            return new ResponseEntity<String>(Roles.toJsonArray(result), headers, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<String>("{\"ERROR\":"+e.getMessage()+"\"}", headers, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

	@RequestMapping(method = RequestMethod.POST, headers = "Accept=application/json")
    public ResponseEntity<String> createFromJson(@RequestBody String json, UriComponentsBuilder uriBuilder) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        try {
            Roles roles = Roles.fromJsonToRoles(json);
            rolesService.saveRoles(roles);
            RequestMapping a = (RequestMapping) getClass().getAnnotation(RequestMapping.class);
            headers.add("Location",uriBuilder.path(a.value()[0]+"/"+roles.getId().toString()).build().toUriString());
            return new ResponseEntity<String>(headers, HttpStatus.CREATED);
        } catch (Exception e) {
            return new ResponseEntity<String>("{\"ERROR\":"+e.getMessage()+"\"}", headers, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

	@RequestMapping(value = "/jsonArray", method = RequestMethod.POST, headers = "Accept=application/json")
    public ResponseEntity<String> createFromJsonArray(@RequestBody String json) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        try {
            for (Roles roles: Roles.fromJsonArrayToRoleses(json)) {
                rolesService.saveRoles(roles);
            }
            return new ResponseEntity<String>(headers, HttpStatus.CREATED);
        } catch (Exception e) {
            return new ResponseEntity<String>("{\"ERROR\":"+e.getMessage()+"\"}", headers, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

	@RequestMapping(value = "/{id}", method = RequestMethod.PUT, headers = "Accept=application/json")
    public ResponseEntity<String> updateFromJson(@RequestBody String json, @PathVariable("id") Integer id) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        try {
            Roles roles = Roles.fromJsonToRoles(json);
            roles.setId(id);
            if (rolesService.updateRoles(roles) == null) {
                return new ResponseEntity<String>(headers, HttpStatus.NOT_FOUND);
            }
            return new ResponseEntity<String>(headers, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<String>("{\"ERROR\":"+e.getMessage()+"\"}", headers, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE, headers = "Accept=application/json")
    public ResponseEntity<String> deleteFromJson(@PathVariable("id") Integer id) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        try {
            Roles roles = rolesService.findRoles(id);
            if (roles == null) {
                return new ResponseEntity<String>(headers, HttpStatus.NOT_FOUND);
            }
            rolesService.deleteRoles(roles);
            return new ResponseEntity<String>(headers, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<String>("{\"ERROR\":"+e.getMessage()+"\"}", headers, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

	@Autowired
    RolesService rolesService;

	@Autowired
    FunctionsService functionsService;

	@Autowired
    SubFunctionsService subFunctionsService;

	@Autowired
    UsersService usersService;

	@RequestMapping(method = RequestMethod.POST, produces = "text/html")
    public String create(@Valid Roles roles, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, roles);
            return "roleses/create";
        }
        uiModel.asMap().clear();
        rolesService.saveRoles(roles);
        return "redirect:/roleses/" + encodeUrlPathSegment(roles.getId().toString(), httpServletRequest);
    }

	@RequestMapping(params = "form", produces = "text/html")
    public String createForm(Model uiModel) {
        populateEditForm(uiModel, new Roles());
        return "roleses/create";
    }

	@RequestMapping(value = "/{id}", produces = "text/html")
    public String show(@PathVariable("id") Integer id, Model uiModel) {
        uiModel.addAttribute("roles", rolesService.findRoles(id));
        uiModel.addAttribute("itemId", id);
        return "roleses/show";
    }

	@RequestMapping(produces = "text/html")
    public String list(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, @RequestParam(value = "sortFieldName", required = false) String sortFieldName, @RequestParam(value = "sortOrder", required = false) String sortOrder, Model uiModel) {
        if (page != null || size != null) {
            int sizeNo = size == null ? 10 : size.intValue();
            final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
            uiModel.addAttribute("roleses", Roles.findRolesEntries(firstResult, sizeNo, sortFieldName, sortOrder));
            float nrOfPages = (float) rolesService.countAllRoleses() / sizeNo;
            uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        } else {
            uiModel.addAttribute("roleses", Roles.findAllRoleses(sortFieldName, sortOrder));
        }
        return "roleses/list";
    }

	@RequestMapping(method = RequestMethod.PUT, produces = "text/html")
    public String update(@Valid Roles roles, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, roles);
            return "roleses/update";
        }
        uiModel.asMap().clear();
        rolesService.updateRoles(roles);
        return "redirect:/roleses/" + encodeUrlPathSegment(roles.getId().toString(), httpServletRequest);
    }

	@RequestMapping(value = "/{id}", params = "form", produces = "text/html")
    public String updateForm(@PathVariable("id") Integer id, Model uiModel) {
        populateEditForm(uiModel, rolesService.findRoles(id));
        return "roleses/update";
    }

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = "text/html")
    public String delete(@PathVariable("id") Integer id, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        Roles roles = rolesService.findRoles(id);
        rolesService.deleteRoles(roles);
        uiModel.asMap().clear();
        uiModel.addAttribute("page", (page == null) ? "1" : page.toString());
        uiModel.addAttribute("size", (size == null) ? "10" : size.toString());
        return "redirect:/roleses";
    }

	void populateEditForm(Model uiModel, Roles roles) {
        uiModel.addAttribute("roles", roles);
        uiModel.addAttribute("functionses", functionsService.findAllFunctionses());
        uiModel.addAttribute("subfunctionses", subFunctionsService.findAllSubFunctionses());
        uiModel.addAttribute("userses", usersService.findAllUserses());
    }

	String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
        String enc = httpServletRequest.getCharacterEncoding();
        if (enc == null) {
            enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
        }
        try {
            pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
        } catch (UnsupportedEncodingException uee) {}
        return pathSegment;
    }
}
